<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="groupPersonVisible"
    width="1200px"
    @close="handleClose"
    :close-on-click-modal="false"
  >
    <el-form
      ref="form"
      :model="currentPerson"
      :rules="rules"
      label-width="150px"
    >
      <!-- 人员基本信息 -->
      <div class="person-header">
        <el-row :gutter="20">
          <el-col :span="16">
            <div class="section-title">人员基本信息</div>
          </el-col>
          <el-col :span="8" style="text-align: right">
            <el-button
              type="danger"
              size="medium"
              @click="deletePerson(currentIndex)"
              style="padding: 10px 20px; font-size: 14px"
            >
              删除该人员
            </el-button>
          </el-col>
        </el-row>
      </div>

      <div class="section-content">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-col :span="12">
              <el-form-item label="作业项目" prop="projectId">
                <el-cascader
                  v-model="currentPerson.projectId"
                  :options="projectOptions"
                  :props="{
                    checkStrictly: true,
                    emitPath: false,
                    value: 'id',
                    label: 'label',
                    children: 'children',
                  }"
                  placeholder="请选择培训项目"
                  style="width: 100%"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-col>
          <el-col :span="24">
            <el-col :span="12">
              <el-form-item label="姓名" prop="studentName">
                <el-input v-model="currentPerson.studentName" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号码" prop="phonenumber">
                <el-input v-model="currentPerson.phonenumber" />
              </el-form-item>
            </el-col>
          </el-col>
          <el-col :span="24">
            <el-col :span="12">
              <el-form-item label="证件类型" prop="documentType">
                <el-select
                  v-model="currentPerson.documentType"
                  style="width: 100%"
                  placeholder="请选择证件类型"
                >
                  <el-option
                    v-for="item in documentTypeOptions"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="证件编号" prop="idNumber">
                <el-input v-model="currentPerson.idNumber" />
              </el-form-item>
            </el-col>
          </el-col>
          <el-col :span="24">
            <el-col :span="12">
              <el-form-item label="证件有效期" prop="validityPeriod">
                <el-date-picker
                  v-model="currentPerson.validityPeriod"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="人员类型" prop="userType">
                <el-input
                  v-model="currentPerson.userType"
                  placeholder="请输入人员类型"
                />
              </el-form-item>
            </el-col>
          </el-col>
          <el-col :span="24">
            <el-col :span="12">
              <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="currentPerson.sex">
                  <el-radio label="男" />
                  <el-radio label="女" />
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出生年月" prop="birthDate">
                <el-date-picker
                  v-model="currentPerson.birthDate"
                  type="date"
                  placeholder="选择日期"
                  value-format="yyyy-MM-dd"
                  style="width: 100%"
                />
              </el-form-item> </el-col
          ></el-col>
          <el-col :span="24"
            ><el-col :span="12">
              <el-form-item label="民族" prop="nation">
                <el-select
                  v-model="currentPerson.nation"
                  style="width: 100%"
                  placeholder="请选择民族"
                >
                  <el-option
                    v-for="item in nationOptions"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="职务" prop="position">
                <el-input
                  v-model="currentPerson.position"
                  placeholder="请输入职务"
                />
              </el-form-item>
            </el-col>
          </el-col>
          <el-col :span="24">
            <el-col :span="12">
              <el-form-item label="学历" prop="qualification">
                <el-select
                  v-model="currentPerson.qualification"
                  style="width: 100%"
                  placeholder="请选择学历"
                >
                  <el-option
                    v-for="item in educationOptions"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-col>
          <el-col :span="24">
            <el-col :span="12">
              <el-form-item label="毕业院校" prop="graduatedFrom">
                <el-input
                  v-model="currentPerson.graduatedFrom"
                  placeholder="请输入毕业院校"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所学专业" prop="major">
                <el-input
                  v-model="currentPerson.major"
                  placeholder="请输入所学专业"
                />
              </el-form-item> </el-col
          ></el-col>
          <el-col :span="24">
            <el-col :span="12">
              <el-form-item label="地址" prop="address">
                <el-input
                  v-model="currentPerson.address"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入详细地址"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮编" prop="postCode">
                <el-input
                  v-model="currentPerson.postCode"
                  placeholder="请输入邮编"
                />
              </el-form-item> </el-col
          ></el-col>
          <el-col :span="24">
            <el-col :span="12">
              <el-form-item label="传真" prop="fax">
                <el-input
                  v-model="currentPerson.fax"
                  placeholder="请输入传真"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="电子邮箱" prop="email">
                <el-input
                  v-model="currentPerson.email"
                  placeholder="请输入电子邮箱"
                />
              </el-form-item>
            </el-col>
          </el-col>
        </el-row>
      </div>

      <!-- 原证书情况 -->
      <div class="section-title">原证书情况</div>
      <div class="section-content">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="原发证机关" prop="originalAuthority">
              <el-input
                v-model="currentPerson.originalAuthority"
                placeholder="请输入原发证机关"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证书编号" prop="certificateNo">
              <el-input
                v-model="currentPerson.certificateNo"
                placeholder="请输入证书编号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发证机关地址" prop="originalAuthorityAddress">
              <el-input
                v-model="currentPerson.originalAuthorityAddress"
                placeholder="请输入发证机关地址"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="首次领证日期" prop="firstIssueDate">
              <el-date-picker
                v-model="currentPerson.firstIssueDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证书到期日期" prop="expireDate">
              <el-date-picker
                v-model="currentPerson.expireDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 单位信息 -->
      <div class="section-title">单位信息</div>
      <div class="section-content">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单位名称" prop="unitName">
              <el-input
                v-model="formData.unitName"
                placeholder="请输入单位名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位统一信用代码" prop="creditCode">
              <el-input
                v-model="formData.creditCode"
                placeholder="请输入单位统一信用代码"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属区域" prop="administrativeArea">
              <el-select
                v-model="formData.administrativeArea"
                style="width: 100%"
                placeholder="请选择所属区域"
              >
                <el-option
                  v-for="item in administrativeAreaOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在单位性质" prop="unitNature">
              <el-select
                v-model="formData.unitNature"
                style="width: 100%"
                placeholder="请选择单位性质"
              >
                <el-option
                  v-for="item in unitNatureOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="单位地址" prop="address">
              <el-input
                v-model="formData.address"
                placeholder="请输入单位地址"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人姓名" prop="contactName">
              <el-input
                v-model="formData.contactName"
                placeholder="请输入联系人姓名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="unitPhonenumber">
              <el-input
                v-model="formData.unitPhonenumber"
                placeholder="请输入手机号码"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 安全管理工作经历 -->
      <div class="section-title">安全管理工作经历</div>
      <div class="section-content">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工作时间" prop="workPeriods">
              <el-date-picker
                v-model="currentPerson.workPeriods[0]"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作企业" prop="workCompany">
              <el-input
                v-model="currentPerson.workCompany[0]"
                placeholder="请输入单位名称，请确保信息正确"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作时间" prop="workPeriods1">
              <el-date-picker
                v-model="currentPerson.workPeriods[1]"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作企业" prop="workCompany1">
              <el-input
                v-model="currentPerson.workCompany[1]"
                placeholder="请输入单位名称，请确保信息正确"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作时间" prop="workPeriods2">
              <el-date-picker
                v-model="currentPerson.workPeriods[2]"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作企业" prop="workCompany2">
              <el-input
                v-model="currentPerson.workCompany[2]"
                placeholder="请输入单位名称，请确保信息正确"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 安全教育和培训情况 -->
      <div class="section-title">安全教育和培训情况</div>
      <div class="section-content">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="培训时间" prop="trainingPeriods">
              <el-date-picker
                v-model="currentPerson.trainingPeriods[0]"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培训情况" prop="trainingSituation">
              <el-input
                v-model="currentPerson.trainingSituation[0]"
                placeholder="请输入培训情况"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培训时间" prop="trainingPeriods1">
              <el-date-picker
                v-model="currentPerson.trainingPeriods[1]"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培训情况" prop="trainingSituation1">
              <el-input
                v-model="currentPerson.trainingSituation[1]"
                placeholder="请输入培训情况"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培训时间" prop="trainingPeriods2">
              <el-date-picker
                v-model="currentPerson.trainingPeriods[2]"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培训情况" prop="trainingSituation2">
              <el-input
                v-model="currentPerson.trainingSituation[2]"
                placeholder="请输入培训情况"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 档案缺失情况 -->
      <div class="section-title">档案缺失情况</div>
      <div class="section-content">
        <el-form-item>
          <el-checkbox-group v-model="currentPerson.archiveMissing">
            <el-checkbox label="全缺" />
            <el-checkbox label="身份证" />
            <el-checkbox label="照片" />
            <el-checkbox label="申请表" />
            <el-checkbox label="学历证明" />
            <el-checkbox label="体检证明" />
            <el-checkbox label="原证书" />
            <el-checkbox label="考试检验记录" />
            <el-checkbox label="记录表" />
          </el-checkbox-group>
        </el-form-item>
      </div>

      <!-- 协议缺失情况 -->
      <div class="section-title">协议缺失情况</div>
      <div class="section-content">
        <el-form-item>
          <el-checkbox v-model="currentPerson.protocolMissing" label="缺协议" />
        </el-form-item>
      </div>

      <!-- 备注 -->
      <div class="section-title">备注</div>
      <div class="section-content">
        <el-row :gutter="20" style="width: 100%">
          <el-col :span="24">
            <el-form-item prop="remark" label-width="0">
              <el-input
                v-model="currentPerson.remark"
                type="textarea"
                :rows="4"
                style="
                  width: 100% !important;
                  max-width: none;
                  box-sizing: border-box;
                "
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <!-- 底部按钮 -->
    <div class="dialog-footer">
      <el-button @click="handlePrev">上一位</el-button>
      <el-button @click="handleNext">下一位</el-button>
      <el-button type="primary" @click="submitForm">提交完成</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { projectTreeSelect } from "@/api/training/projects";
import { getDicts } from "@/api/system/dict/data";
import { addGroup } from "@/api/training/registration";
export default {
  name: "AddGroupPersonReview",
  props: {
    // 接收从 AddGroupReexamination 传入的单位信息
    unitInfo: {
      type: Object,
      default: () => ({}),
    },
    dictData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      // 当前正在编辑的人员索引
      currentIndex: 0,
      // 人员列表
      persons: [],
      // 当前人员数据（用于表单绑定）
      currentPerson: {
        // 人员基本信息
        jobType: "",
        projectId: "",
        studentName: "",
        phonenumber: "",
        documentType: "IDCARD",
        idNumber: "",
        validityPeriod: [],
        userType: "",
        sex: "男",
        birthDate: "",
        nation: "",
        position: "",
        qualification: "",
        major: "",
        graduatedFrom: "",
        address: "",
        postCode: "",
        fax: "",
        email: "",

        // 原证书情况
        originalAuthority: "",
        certificateNo: "",
        originalAuthorityAddress: "",
        firstIssueDate: "",
        expireDate: "",

        // 安全管理工作经历
        workPeriods: ["", "", ""],
        workCompany: ["", "", ""],

        // 安全教育和培训情况
        trainingPeriods: ["", "", ""],
        trainingSituation: ["", "", ""],

        // 档案缺失情况
        archiveMissing: [],
        protocolMissing: false,

        // 备注
        remark: "",
      },
      // 当前人员数据（用于表单绑定）
      formData: {
        // 人员基本信息
        jobType: "",
        projectId: "",
        studentName: "",
        phonenumber: "",
        documentType: "IDCARD",
        idNumber: "",
        validityPeriod: [],
        userType: "",
        sex: "男",
        birthDate: "",
        nation: "",
        position: "",
        qualification: "",
        major: "",
        graduatedFrom: "",
        address: "",
        postCode: "",
        fax: "",
        email: "",

        // 原证书情况
        originalAuthority: "",
        certificateNo: "",
        originalAuthorityAddress: "",
        firstIssueDate: "",
        expireDate: "",

        // 安全管理工作经历
        workPeriods: ["", ""],
        workCompany: ["", ""],

        // 安全教育和培训情况
        trainingPeriods: ["", ""],
        trainingSituation: ["", ""],

        // 档案缺失情况
        archiveMissing: [],
        protocolMissing: false,

        // 备注
        remark: "",
      },

      // 表单规则（参考 AddPersonalReview）
      rules: {
        projectId: [
          { required: true, message: "请选择作业项目", trigger: "change" },
        ],
        studentName: [
          { required: true, message: "请输入姓名", trigger: "blur" },
        ],
        phonenumber: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
        ],
        documentType: [
          { required: true, message: "请选择证件类型", trigger: "change" },
        ],
        idNumber: [
          { required: true, message: "请输入证件编号", trigger: "blur" },
        ],
        sex: [{ required: true, message: "请选择性别", trigger: "change" }],
        birthDate: [
          { required: true, message: "请选择出生年月", trigger: "change" },
        ],
        address: [
          { required: true, message: "请输入详细地址", trigger: "blur" },
        ],
        postCode: [{ required: true, message: "请输入邮编", trigger: "blur" }],
        email: [{ required: true, message: "请输入电子邮箱", trigger: "blur" }],

        originalAuthority: [
          { required: true, message: "请输入原发证机关", trigger: "blur" },
        ],
        certificateNo: [
          { required: true, message: "请输入证书编号", trigger: "blur" },
        ],
        originalAuthorityAddress: [
          { required: true, message: "请输入发证机关地址", trigger: "blur" },
        ],
        firstIssueDate: [
          { required: true, message: "请选择首次领证日期", trigger: "change" },
        ],
        expireDate: [
          { required: true, message: "请选择证书到期日期", trigger: "change" },
        ],

        workPeriods: [
          { required: true, message: "请选择工作时间", trigger: "change" },
        ],
        workCompany: [
          { required: true, message: "请输入工作企业", trigger: "blur" },
        ],
        trainingPeriods: [
          { required: true, message: "请选择培训时间", trigger: "change" },
        ],
        trainingSituation: [
          { required: true, message: "请输入培训情况", trigger: "blur" },
        ],
      },

      // 下拉选项
      projectOptions: [],
      documentTypeOptions: [],
      unitNatureOptions: [],
      educationOptions: [],
      nationOptions: [],
      administrativeAreaOptions: [],
      dialogTitle: "集体复审人员信息",
      groupPersonVisible: false,
    };
  },
  created() {
    this.getProjectTree();2
    // this.initDictData();
  },
  watch: {
    dictData: {
      handler(newVal) {
        if (newVal !== null) {
          this.getProjectTree();
          this.initDictData();
        }
      },
      deep: true,
    },
  },
  methods: {
    initDictData() {
      this.unitNatureOptions = this.dictData.unitNatureOptions;
      this.documentTypeOptions = this.dictData.documentTypeOptions;
      this.nationOptions = this.dictData.nationOptions;
      this.educationOptions = this.dictData.educationOptions;
      this.administrativeAreaOptions = this.dictData.administrativeAreaOptions;
    },
    // 获取项目树形数据
    getProjectTree() {
      projectTreeSelect({}).then((response) => {
        this.projectOptions = response.data;
      });
    },
    //   open 方法以支持从父组件打开对话框
    open(unitInfo) {
      this.groupPersonVisible = true;
      // 将传入的单位信息赋值给表单数据
      if (unitInfo) {
        this.formData = {
          unitName: unitInfo.unitName || "",
          creditCode: unitInfo.creditCode || "",
          administrativeArea: unitInfo.administrativeArea || "",
          unitNature: unitInfo.unitNature || "",
          address: unitInfo.address || "",
          contactName: unitInfo.contactName || "",
          unitPhonenumber: unitInfo.unitPhonenumber || "",
        };
      }
    },
    //   handleClose 方法
    handleClose() {
      this.groupPersonVisible = false;
      // 重置索引和人员列表
      this.currentIndex = 0;
      this.persons = [];

      // 重置表单数据
      this.resetFormData();
    },
    // 添加 handlePrev 方法
    handlePrev() {
      if (this.currentIndex > 0) {
        // 保存当前人员数据
        this.$set(this.persons, this.currentIndex, { ...this.currentPerson });
        this.currentIndex--;
        this.currentPerson = { ...this.persons[this.currentIndex] };
      }
    },

    // 添加 handleNext 方法（模板中已引用但未定义）
    handleNext() {
      // 保存当前人员数据
      this.$set(this.persons, this.currentIndex, { ...this.currentPerson });
      if (this.currentIndex < this.persons.length - 1) {
        this.currentIndex++;
        this.currentPerson = { ...this.persons[this.currentIndex] };
      } else {
        // 如果是最后一个人，添加新人员
        this.addPerson();
      }
    },
    // 添加 submitForm 方法（模板中已引用但未定义）
    submitForm() {
      console.log("提交数据：", this.persons);
      this.submitAll();
    },
    // 添加新人员
    addPerson() {
      this.persons.push({ ...this.formData });
      this.resetForm();
      this.currentIndex = this.persons.length - 1;
    },

    // 删除当前人员
    deletePerson(index) {
      if (this.persons.length <= 1) {
        this.$message.warning("至少保留一名人员");
        return;
      }
      this.persons.splice(index, 1);
      if (index === this.currentIndex) {
        this.currentIndex = Math.max(0, index - 1);
      }
      this.resetForm();
    },
    // 新增 resetFormData 方法
    resetFormData() {
      // 重置 formData
      this.formData = {
        jobType: "",
        projectId: "",
        studentName: "",
        phonenumber: "",
        documentType: "IDCARD",
        idNumber: "",
        validityPeriod: [],
        userType: "",
        sex: "男",
        birthDate: "",
        nation: "",
        position: "",
        qualification: "",
        major: "",
        graduatedFrom: "",
        address: "",
        postCode: "",
        fax: "",
        email: "",
        originalAuthority: "",
        certificateNo: "",
        originalAuthorityAddress: "",
        firstIssueDate: "",
        expireDate: "",
        workPeriods: ["", "", ""],
        workCompany: ["", "", ""],
        trainingPeriods: ["", "", ""],
        trainingSituation: ["", "", ""],
        archiveMissing: [],
        protocolMissing: false,
        remark: "",
      };

      // 重置当前人员数据
      this.resetForm();
    },
    // 切换到上一位
    prevPerson() {
      if (this.currentIndex > 0) {
        this.currentIndex--;
        this.formData = { ...this.persons[this.currentIndex] };
      }
    },

    // 切换到下一位
    nextPerson() {
      if (this.currentIndex < this.persons.length - 1) {
        this.currentIndex++;
        this.formData = { ...this.persons[this.currentIndex] };
      }
    },

    // 重置表单

    resetForm() {
      // 添加安全检查，确保 $refs.form 存在再调用 resetFields
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
      this.currentPerson = {
        jobType: "",
        projectId: "",
        studentName: "",
        phonenumber: "",
        documentType: "IDCARD",
        idNumber: "",
        validityPeriod: [],
        userType: "",
        sex: "男",
        birthDate: "",
        nation: "",
        position: "",
        qualification: "",
        major: "",
        graduatedFrom: "",
        address: "",
        postCode: "",
        fax: "",
        email: "",
        originalAuthority: "",
        certificateNo: "",
        originalAuthorityAddress: "",
        firstIssueDate: "",
        expireDate: "",
        workPeriods: ["", "", ""],
        workCompany: ["", "", ""],
        trainingPeriods: ["", "", ""],
        trainingSituation: ["", "", ""],
        archiveMissing: [],
        protocolMissing: false,
        remark: "",
      };
    },

    // 提交所有人员数据
    submitAll() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 保存当前正在编辑的人员数据
          this.$set(this.persons, this.currentIndex, { ...this.currentPerson });

          // 过滤掉空数据，只提交有实际内容的数据
          const validPersons = this.persons.filter((person) => {
            return (
              person.studentName ||
              person.phonenumber ||
              person.idNumber ||
              person.projectId
            );
          });

          if (validPersons.length === 0) {
            this.$message.error("请至少填写一名人员信息");
            return;
          }

          // 构造最终提交数据
          const submitData = {
            unitInfo: {
              unitName: this.formData.unitName,
              creditCode: this.formData.creditCode,
              administrativeArea: this.formData.administrativeArea,
              unitNature: this.formData.unitNature,
              address: this.formData.address,
              contactName: this.formData.contactName,
              unitPhonenumber: this.formData.unitPhonenumber,
            },
            personList: this.persons.map((person) => {
              const validityPeriod = Array.isArray(person.validityPeriod)
                ? person.validityPeriod
                : [];
              const [start, end] =
                validityPeriod.length >= 2
                  ? [validityPeriod[0], validityPeriod[1]]
                  : [null, null];

              // 安全检查工作经历数组
              const workPeriods = Array.isArray(person.workPeriods)
                ? person.workPeriods
                : ["", "", ""];
              const workCompany = Array.isArray(person.workCompany)
                ? person.workCompany
                : ["", "", ""];

              const workExperience = [];
              for (let i = 0; i < 3; i++) {
                const period = workPeriods[i];
                const company = workCompany[i];
                if (period && period[0] && period[1] && company) {
                  workExperience.push({
                    period: `${period[0]}至${period[1]}`,
                    company,
                  });
                }
              }

              // 安全检查培训情况数组
              const trainingPeriods = Array.isArray(person.trainingPeriods)
                ? person.trainingPeriods
                : ["", "", ""];
              const trainingSituation = Array.isArray(person.trainingSituation)
                ? person.trainingSituation
                : ["", "", ""];

              const trainingExperience = [];
              for (let i = 0; i < 3; i++) {
                const period = trainingPeriods[i];
                const situation = trainingSituation[i];
                if (period && period[0] && period[1] && situation) {
                  trainingExperience.push({
                    period: `${period[0]}至${period[1]}`,
                    situation,
                  });
                }
              }

              return {
                ...person,
                trainingType: "3",
                certificateStarttime: start,
                certificateEndtime: end,
                workResume: workExperience
                  .map(
                    (item) =>
                      `${item.period}，在${item.company}从事特种设备安全管理工作`
                  )
                  .join("; "),
                trainingExperience: trainingExperience
                  .map((item) => `${item.period}，培训情况：${item.situation}`)
                  .join("; "),
                // 删除原始数组字段
                workPeriods: undefined,
                workCompany: undefined,
                trainingPeriods: undefined,
                trainingSituation: undefined,
                validityPeriod: undefined,
              };
            }),
          };

          // 调用 API 提交数据
          console.log("提交数据666:", submitData);
          addGroup(submitData);
          this.$message.success("提交成功");
          this.groupPersonVisible = false;
          this.$emit("submit-complete", submitData); // 触发父组件事件
        } else {
          this.$message.error("请填写完整信息");
        }
      });
    },
  },
};
</script>
<style scoped>
/* 区块标题样式 */
.section-title {
  font-weight: bold;
  font-size: 20px;
  padding: 10px 0;
  margin-bottom: 10px;
}

/* 区块内容容器 */
.section-content {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  border: 1px solid #ddd;
  padding: 16px;
  background-color: #fff;
  margin-bottom: 20px;
}

/* 每个字段组（label + input） */
.field-group {
  flex: 1;
  min-width: 200px;
  display: flex;
  flex-direction: column;
}

/* 标签样式 */
.field-group label {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
  font-weight: bold;
}

/* 输入框样式 */
.field-group .el-input,
.field-group .el-select,
.field-group .el-date-editor,
.field-group .el-radio-group {
  width: 100%;
  max-width: 300px;
}

/* 布局优化：让两列对齐 */
.section-content > .field-group:nth-child(odd) {
  margin-right: 16px;
}

/* 确保所有元素垂直对齐 */
.field-group {
  align-items: flex-start;
}

/* 调整 el-form-item 的默认样式 */
.el-form-item {
  margin-bottom: 8px;
}

/* 隐藏 el-form-item 的默认边距 */
.el-form-item__label {
  padding: 0;
  line-height: 1.2;
}

/* 精准定位“档案缺失情况”和“协议缺失情况”的 el-form-item，去除左侧空白 */
.section-title + .section-content .el-form-item {
  margin-left: 0 !important;
  padding-left: 0 !important;
}

/* 可选：进一步控制 checkbox 的对齐 */
.section-content .el-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
  margin: 0;
}

.section-content .el-checkbox {
  margin-right: 8px;
}

.person-header {
  margin-bottom: 16px;
}

.section-title {
  font-weight: bold;
  font-size: 20px;
  padding: 10px 0;
  margin-bottom: 0;
}
</style>

